import { BASE_URL, USE_MOCK_DATA, ErrorMessages, ApiResponseCode, StorageKeys } from './config'

/**
 * 自定义请求错误类
 */
class RequestError extends Error {
  constructor(message, code) {
    super(message)
    this.code = code
  }
}

/**
 * 请求类
 * 处理HTTP请求
 */
export class Request {
  constructor(baseURL = BASE_URL) {
    this.baseURL = baseURL
    this.interceptors = {
      request: [],
      response: []
    }
    
    // 添加默认拦截器
    this.interceptors.request.push(config => {
      const token = uni.getStorageSync(StorageKeys.TOKEN)
      if (token) {
        config.header = {
          ...config.header,
          'Authorization': `Bearer ${token}`
        }
      }
      return config
    })
    
    this.interceptors.response.push(response => {
      if (response.statusCode === ApiResponseCode.UNAUTHORIZED) {
        // 清除token和用户信息
        uni.removeStorageSync(StorageKeys.TOKEN)
        uni.removeStorageSync(StorageKeys.USER_INFO)
        
        // 获取当前页面路径
        const pages = getCurrentPages()
        const currentPage = pages[pages.length - 1]
        const currentPath = currentPage ? currentPage.route : ''
        
        // 如果当前不是登录页，则跳转到登录页
        if (currentPath !== 'pages/user/register') {
          // 使用redirectTo而不是navigateTo，避免返回到需要登录的页面
          uni.redirectTo({
            url: '/pages/user/register',
            fail: () => {
              // 如果redirectTo失败，尝试使用reLaunch
              uni.reLaunch({
                url: '/pages/user/register'
              })
            }
          })
        }
        
        throw new RequestError(ErrorMessages.UNAUTHORIZED, ApiResponseCode.UNAUTHORIZED)
      }
      return response
    })
  }

  // 添加请求拦截器
  addRequestInterceptor(interceptor) {
    this.interceptors.request.push(interceptor)
  }

  // 添加响应拦截器
  addResponseInterceptor(interceptor) {
    this.interceptors.response.push(interceptor)
  }

  // 处理请求配置
  async processRequestConfig(config) {
    for (const interceptor of this.interceptors.request) {
      config = await interceptor(config)
    }
    return config
  }

  // 处理响应数据
  async processResponse(response) {
    for (const interceptor of this.interceptors.response) {
      response = await interceptor(response)
    }
    return response
  }

  // 发送请求
  async request(config) {
    try {
      config = await this.processRequestConfig({
        ...config,
        url: this.baseURL + config.url
      })

      return new Promise((resolve, reject) => {
        uni.request({
          ...config,
          success: async (response) => {
            try {
              const processedResponse = await this.processResponse(response)
              if (processedResponse.statusCode >= 200 && processedResponse.statusCode < 300) {
                resolve(processedResponse.data)
              } else {
                reject(new RequestError(
                  processedResponse.data?.message || ErrorMessages.SERVER_ERROR,
                  processedResponse.statusCode
                ))
              }
            } catch (error) {
              reject(error)
            }
          },
          fail: (error) => {
            reject(new RequestError(ErrorMessages.NETWORK_ERROR))
          }
        })
      })
    } catch (error) {
      throw error
    }
  }

  // GET请求
  get(url, params = {}, config = {}) {
    return this.request({
      url,
      method: 'GET',
      data: params,
      ...config
    })
  }

  // POST请求
  post(url, data = {}, config = {}) {
    return this.request({
      url,
      method: 'POST',
      data,
      ...config
    })
  }

  // PUT请求
  put(url, data = {}, config = {}) {
    return this.request({
      url,
      method: 'PUT',
      data,
      ...config
    })
  }

  // DELETE请求
  delete(url, config = {}) {
    return this.request({
      url,
      method: 'DELETE',
      ...config
    })
  }

  // 上传文件
  upload(url, filePath, formData = {}, config = {}) {
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: this.baseURL + url,
        filePath,
        name: 'file',
        formData,
        ...(config || {}),
        success: (uploadResponse) => {
          try {
            // 尝试解析响应
            const data = JSON.parse(uploadResponse.data)
            resolve(data)
          } catch (error) {
            reject(new RequestError(ErrorMessages.UPLOAD_FAILED))
          }
        },
        fail: (error) => {
          reject(new RequestError(ErrorMessages.UPLOAD_FAILED + ': ' + (error.errMsg || '未知错误')))
        }
      })
    })
  }
}

// 创建默认实例
const request = new Request()
export default request